package edu.school.controller;

import com.github.pagehelper.PageInfo;
import edu.school.entity.User;
import edu.school.service.UserService;
import edu.school.utils.ImgUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.util.Date;

/**
 * @author kabuda
 * @create 2023-10-01 15:11
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "pageList")
    public String getPageList(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize" ,defaultValue = "5") Integer pageSize, User user, Model model) {
        PageInfo<User> userPageInfo = userService.pageList(pageNum, pageSize, user);
        model.addAttribute("pageInfo",userPageInfo);
        return "user/list";
    }

    /**
     * 跳转编辑页面，回显数据
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "toEdit",method = RequestMethod.GET)
    public String toEdit(Integer id,Model model) {
       User user=userService.findById(id);
       model.addAttribute("record",user);
        return "user/edit";
    }

    /**
     * 编辑
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "edit",method = RequestMethod.POST)
    public String edit(User user){

        if(userService.edit(user)){
            return "<script>alert('success');location.href='/user/pageList'</script>";
        }else{
            return "<script>alert('fail');history.to(-1)</script>";
        }
    }

    @ResponseBody
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public String delete(Integer id){
        boolean result = userService.delete(id);
        if(result){
            return "ok";
        }else{
            return "fail";
        }
    }
    @ResponseBody
    @RequestMapping(value = "deletemany",method = RequestMethod.POST)
    public String deletemany(int[] ids){
        boolean result = userService.deletemany(ids);
        if(result){
            return "ok";
        }else{
            return "fail";
        }
    }
}
